import os
import dify_helper
import pandas as pd
import argparse
import configparser
import cv2
import imutils
import uuid
import requests
import json

def download_img(img_web_path:str):
    img_path = os.path.join("temp",str(uuid.uuid4())+".jpg")
    if not os.path.exists("temp"):
        os.mkdir("temp")
    r = requests.get(img_web_path)
    with open(img_path, 'wb') as f:
        f.write(r.content)
    return img_path

def roate_img(img_path:str,rotate_angle:int):
    img = cv2.imread(img_path)
    if img is None:
        return None
    try:
        rotated = imutils.rotate_bound(img, angle=rotate_angle)
        cv2.imwrite(img_path, rotated)
    except:
        print("旋转失败")
        print(img_path)
        cv2.imwrite(img_path, img)
    return img_path


def run_vlmodel_first(row:dict,query:str,dh:dify_helper.DifyHelper):
    if row["comment"] == None:
        return "无图片"
    img_path = download_img(row["comment"])
    with open(img_path, "rb") as f:
        tmp_file_id = dh.upload_file({'file': (img_path, f, 'image/jpg')})
    paramters = {
        "image_path":{
            "type": "image",
            "transfer_method": "local_file",
            "upload_file_id": tmp_file_id
        },
    }
    try:
        answer_str = dh.send_json_message_get_json_result(paramters,query)
        answer = json.loads(answer_str)
        if answer["is_clear"] == True and answer["is_word_angle_right"] == False:
            roate_img(img_path,answer["need_rotate_angle"])
        answer["image_path"] = img_path
        answer = json.dumps(answer)
    except Exception as ex:
        print(ex)
        answer = "解读失败"
    return answer

def run_get_rotate_image_path(row:dict):
    if row["视觉-前置识别结果"] == None:
        return ""
    f_answer = json.loads(row["视觉-前置识别结果"])
    if f_answer["is_clear"] == False:
        return ""
    if f_answer["report_type"] == "无法确定":
        return ""
    if "image_path" not in f_answer:
        return ""
    return f_answer["image_path"]
def run_vlmodel_recongnize(row:dict,query:str,dh:dify_helper.DifyHelper):
    if row["视觉-前置识别结果"] == None:
        return "无图片"
    f_answer = json.loads(row["视觉-前置识别结果"])
    if f_answer["is_clear"] == False:
        return "图片不清晰"
    if f_answer["report_type"] == "无法确定":
        return "无法确定报告类型"
    print(f_answer)
    img_path = f_answer["image_path"]
    with open(img_path, "rb") as f:
        tmp_file_id = dh.upload_file({'file': (img_path, f, 'image/jpg')})
    paramters = {
        "image_path":{
            "type": "image",
            "transfer_method": "local_file",
            "upload_file_id": tmp_file_id
        },
    }
    # print(paramters)
    try:
        answer = dh.send_json_message(paramters,query)
    except Exception as ex:
        print(ex)
        answer = "解读失败"
    # print(answer)
    return answer

def run_dify_batch(data_excel_path:str,out_excel_path:str):
    data_df = pd.read_excel(data_excel_path)
    dh_vlf = dify_helper.DifyHelper("http://39.96.64.172:18863/v1","app-7oad9llDZgiP7d9UgNzE2QDu")
    data_df['视觉-前置识别结果'] = data_df.apply(lambda x:run_vlmodel_first(x,"开始识别",dh_vlf),axis=1)

    data_df['旋转后图片地址'] = data_df.apply(lambda x:run_get_rotate_image_path(x),axis=1)

    dh_vlr = dify_helper.DifyHelper("http://39.96.64.172:18863/v1","app-3gBWyKO79Htcby0xaXt1LFHW")
    data_df['视觉模型识别结果'] = data_df.apply(lambda x:run_vlmodel_recongnize(x,"开始识别",dh_vlr),axis=1)
    data_df.to_excel(out_excel_path)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="dify批量运行器")
    parser.add_argument('-rep',"--raw_excel_path", type = str, help = "原始excel文件地址")
    parser.add_argument('-oep',"--out_excel_path", type = str, help = "输出excel文件地址")
    args = parser.parse_args()
    raw_excel_path = args.raw_excel_path
    out_excel_path = args.out_excel_path
    
    run_dify_batch(raw_excel_path,out_excel_path)